<?php
namespace Common\Service;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

//use Qiniu\Storage\BucketManager;

class Qiniu
{

    private static $_accessKey;
    private static $_secretKey;
    private static $_bucket;

    private static function __init()
    {
        SELF::$_accessKey = C('qiniu_config')['accessKey'];
        SELF::$_secretKey = C('qiniu_config')['secretKey'];
        SELF::$_bucket    = C('qiniu_config')['bucket'];
        vendor('Qiniu.autoload');
    }

    //返回七牛外链接地址
    public static function getDomain()
    {
        $token = SELF::getToken();
        return C('qiniu_config')['domain'];
    }

    //获取token，需要设置一个有效时间，避免反复请求服务器
    public static function getToken()
    {
        SELF::__init();
        $auth = new Auth(SELF::$_accessKey, SELF::$_secretKey);
        // 生成上传Token
        $token = $auth->uploadToken(SELF::$_bucket);
        return $token;
    }

    // //获取某一个空间的文件资源
    // public static function getList()
    // {
    //     SELF::__init();
    //     $auth = new Auth(SELF::$_accessKey, SELF::$_secretKey);
    //     $bkt  = new BucketManager($auth);
    //     $lst  = $bkt->listFiles(SELF::$_bucket);
    //     return $lst;
    // }

    // //删除空间文件
    // public static function delImage($bucket, $key)
    // {
    //     $auth = new Auth($this->_accessKey, $this->_secretKey);
    //     $bkt  = new BucketManager($auth);
    //     $ret  = $bkt->delete($bucket, $key);
    //     return $ret;
    // }

    //上传图片
    public static function upload($filePath)
    {
        $token    = SELF::getToken();
        $filePath = 'C:/Users/Administrator/Desktop/3.jpg';
        $key      = '3.jpg';

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        // 构建 UploadManager 对象

        //$err->getResponse()->error;//获取错误信息
        // $err->getResponse()->statusCode;//获取错误code(614表示文件已经存在)
        if ($err !== null) {
            var_dump($err);
        } else {
            //返回上传图片的链接
            //array(2) { ["hash"]=> string(28) "FgeHrhEt_6Yu2Vl2PVl-YdAHJVAZ" ["key"]=> string(5) "3.jpg" }
            $imgurl = SELF::getDomain() . '/' . $ret['key'];
            return $imgurl;
        }
    }
}
